import { formatGMTDate, compareObject, toPercent } from "../../../../assets/js/util.js";
import advance from "../advancedFilter.vue";
import echarts from "echarts";
export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: "",
            DP: {
                p: "",
                f: ""
            },
            // title
            title: "回流分析",
            xlsxTitle: "",
            xlsxTitleQ: "",
            /* 的宽*/
            pageWidth: "100%",
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            /*当前页显示数量*/
            pageSize1: 10,
            /*每页显示的数量*/
            pageSizes1: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal1: 0,
            /*分页器*/
            currentPage1: 1,
            // 选择的时间
            date: "",
            // 渠道数组
            plats: [],
            // 渠道数组
            channels: [],
            // 服务器数组
            servers: [],
            // 默认选择 回流用户菜单
            activeIndex: "1",
            // 默认选择 回流设备菜单
            activeIndex1: "1",
            // 默认的一些时间范围
            pickerOptions: {
                shortcuts: [{
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit("pick", [start, end]);
                        }
                    },
                    {
                        text: "最近15天",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                            picker.$emit("pick", [start, end]);
                        }
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit("pick", [start, end]);
                        }
                    }
                ]
            },
            postObj: {
                dstart: "",
                dend: "",
                platform: "0",
                channel: "0",
                server: "0"
            },
            // 回流用户数据 表头
            tableHeader: [{
                    prop: "dateStr",
                    label: "日期",
                    width: "110px",
                    fixed: true
                },
                {
                    prop: "backuser7day",
                    label: "7日回流用户",
                    width: "150"
                },
                {
                    prop: "backrate7day",
                    label: "7日回流用户占比",
                    width: "180"
                },
                {
                    prop: "backvipuser7day",
                    label: "7日回流VIP用户",
                    width: "170"
                },
                {
                    prop: "backviprate7day",
                    label: "7日回流VIP用户占比",
                    width: "200"
                },
                {
                    prop: "backuser14day",
                    label: "14日回流用户",
                    width: "150"
                },
                {
                    prop: "backrate14day",
                    label: "14日回流用户占比",
                    width: "180"
                },
                {
                    prop: "backvipuser14day",
                    label: "14日回流VIP用户",
                    width: "170"
                },
                {
                    prop: "backviprate14day",
                    label: "14日回流VIP用户占比",
                    width: "200"
                },
                {
                    prop: "backuser30day",
                    label: "30日回流用户",
                    width: "150"
                },
                {
                    prop: "backrate30day",
                    label: "30日回流用户占比",
                    width: "180"
                },
                {
                    prop: "backvipuser30day",
                    label: "30日回流VIP用户",
                    width: "170"
                },
                {
                    prop: "backviprate30day",
                    label: "30日回流VIP用户占比",
                    width: "200"
                },
            ],
            // 回流设备数据 表头
            tableHeader1: [{
                    prop: "dateStr",
                    label: "日期",
                    width: "110px",
                    fixed: true
                },
                {
                    prop: "macOldUser7day",
                    label: "7日回流老账号设备",
                    width: "180"
                },
                {
                    prop: "oldUserMacRate7day",
                    label: "7日回流老账号设备占比",
                    width: "210"
                },
                {
                    prop: "macNewUser7day",
                    label: "7日回流新增账号设备",
                    width: "200"
                },
                {
                    prop: "newUserMacRate7day",
                    label: "7日回流新增账号设备占比",
                    width: "230"
                },
                {
                    prop: "macOldUser14day",
                    label: "14日回流老账号设备",
                    width: "190"
                },
                {
                    prop: "oldUserMacRate14day",
                    label: "14日回流老账号设备占比",
                    width: "220"
                },
                {
                    prop: "macNewUser14day",
                    label: "14日回流新增账号设备",
                    width: "200"
                },
                {
                    prop: "newUserMacRate14day",
                    label: "14日回流新增账号设备占比",
                    width: "230"
                },
                {
                    prop: "macOldUser30day",
                    label: "30日回流老账号设备",
                    width: "190"
                },
                {
                    prop: "oldUserMacRate30day",
                    label: "30日回流老账号设备占比",
                    width: "220"
                },
                {
                    prop: "macNewUser30day",
                    label: "30日回流新增账号设备",
                    width: "200"
                },
                {
                    prop: "newUserMacRate30day",
                    label: "30日回流新增账号设备占比",
                    width: "230"
                }
            ],
            // 数据切换
            dau: [],
            newUser: [],
            oldUser: [],
            tableData: [],
            tableDataAll: [],
            tableData1: [],
            tableDataAll1: [],
            // 图表数据
            real: {
                color: ['#5793f3', '#d14a61', '#675bba'],
                tooltip: {
                    trigger: 'axis',
                    formatter: function(a) {
                        var temp = '';
                        for (var i = 0, len = a.length; i < len; i++) {
                            if (a[i].seriesName.indexOf("占比") < 0) {
                                temp = temp + a[i].seriesName + '：' + a[i].value + '</br>';
                            } else {
                                temp = temp + a[i].seriesName + '：' + Number(a[i].value * 100).toFixed(2) + '%' + '</br>';
                            }
                        }
                        return "日期：" + a[0].name + '</br>' + temp;
                    }
                },
                legend: {
                    top: "10px",
                    data: []
                },
                grid: {
                    left: "1%",
                    right: "2%",
                    bottom: "15%",
                    containLabel: true
                },
                toolbox: {
                    right: "20",
                    feature: {
                        dataZoom: {
                            yAxisIndex: "none"
                        },
                        magicType: {
                            type: ["line", "bar"]
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: "category",
                    data: [],
                    axisLabel: {
                        margin: 20
                    }
                },
                yAxis: [{
                        type: 'value',
                        splitLine: { show: false },
                        name: '数量',
                    },
                    {
                        type: 'value',
                        name: '占比(%)',
                        splitLine: { show: false },
                        axisLabel: {
                            formatter: function(value) {
                                if (typeof(value) == "number") {
                                    var str = (value * 100).toFixed(2);
                                } else {
                                    var str = Number(value * 100).toFixed(2)
                                }
                                str += "%";
                                return str;
                            }
                        }
                    }
                ],
                dataZoom: [{
                    handleIcon: "M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z",
                    handleSize: "80%",
                    handleStyle: {
                        color: "#fff",
                        shadowBlur: 3,
                        shadowColor: "rgba(0, 0, 0, 0.6)",
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                }],
                series: [{
                    name: "",
                    type: "bar",
                    barGap: "20%",
                    barMaxWidth: '50',
                    yAxisIndex: 0,
                    data: [

                    ],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: "#66cf97" },
                                { offset: 0.5, color: "#4eb59a" },
                                { offset: 1, color: "#349b98" }
                            ])
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: "#4eb59a" },
                                { offset: 0.7, color: "#349b98" },
                                { offset: 1, color: "#66cf97" }
                            ])
                        }
                    }
                }, {
                    name: "",
                    type: "bar",
                    barMaxWidth: '50',
                    yAxisIndex: 0,
                    data: [

                    ],
                    itemStyle: {
                        normal: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#b8cff1' },
                                    { offset: 0.5, color: '#a99ce4' },
                                    { offset: 1, color: '#a07cdc' }
                                ]
                            )
                        },
                        emphasis: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1, [
                                    { offset: 0, color: '#a07cdc' },
                                    { offset: 0.7, color: '#a99ce4' },
                                    { offset: 1, color: '#b8cff1' }
                                ]
                            )
                        }
                    }
                }, {
                    name: "",
                    type: 'line',
                    yAxisIndex: 1,
                    smooth: true,
                    data: []
                }, {
                    name: "",
                    type: 'line',
                    yAxisIndex: 1,
                    smooth: true,
                    data: [],
                    symbol: 'triangle',
                }, ]
            },
            // 回流分析-数据指标说明：
            introduce1: [{
                    title: "7日回流",
                    message: "截止某日前，连续7天没有登录游戏的用户，如：1日到7日没有登录过游戏，但在8日登录过游戏，视为7日回流"
                },
                {
                    title: "14日回流",
                    message: "截止某日前，连续14天没有登录游戏的用户，如：1日到14日没有登录过游戏，但在15日登录过游戏，视为14日回流"
                },
                {
                    title: "回流用户",
                    message: "在某段时间内没有登录过游戏但在下一日登录的用户"
                },
                {
                    title: "回流VIP用户",
                    message: "在某段时间内没有登录过游戏但在下一日登录的VIP(付费)用户"
                },
                {
                    title: "回流用户占比",
                    message: "某日回流用户/某日所有活跃用户"
                },
                {
                    title: "回流VIP用户占比",
                    message: "某日回流VIP用户/某日所有VIP活跃用户"
                }
            ],
            // 回流分析-数据指标说明：
            introduce2: [{
                    title: "7日回流",
                    message: "截止某日前，连续7天没有登录游戏的设备，如：1日到7日没有登录过游戏，但在8日登录游戏，视为7日回流"
                },
                {
                    title: "14日回流",
                    message: "截止某日前，连续14天没有登录游戏的设备，如：1日到14日没有登录过游戏，但在15日登录游戏，视为14日回流"
                },
                {
                    title: "回流老账号设备",
                    message: "在某段时间内没有登录过游戏但在下一日登录的老账号设备"
                },
                {
                    title: "回流新增账号设备",
                    message: "在某段时间内没有登录过游戏但在下一日登录的新增账号设备"
                },
                {
                    title: "回流老账号设备占比",
                    message: "某日回流老账号设备/某日所有活跃老账号设备"
                },
                {
                    title: "回流新增账号设备占比",
                    message: "某日回流新账号设备/某日所有新增账号设备"
                }
            ],
            // 存放所有数据
            allData: []
        };
    },
    methods: {
        //初始化
        _init() {
            window.addEventListener(
                "resize",
                function() {
                    this.realTimeDataChart.resize();
                    this.realTimeDataChart2.resize();
                }.bind(this)
            );
        },
        // 表格下载
        excel(tableIndex, sheet) {
            var that = this;
            if (that.postObj.platform == "0") {
                that.xlsxTitleQ = "全平台";
            } else if (that.postObj.platform == "3") {
                that.xlsxTitleQ = "安卓";
            } else if (that.postObj.platform == "2") {
                that.xlsxTitleQ = "ios";
            } else if (that.postObj.platform == "9") {
                that.xlsxTitleQ = "通用";
            }
            that.xlsxTitle =
                sheet +
                "-" +
                that.xlsxTitleQ +
                "-" +
                that.postObj.dstart +
                "到" +
                that.postObj.dend;
            that.downloadExl(
                that["tableHeader" + tableIndex],
                that["tableDataAll" + tableIndex],
                that.xlsxTitle,
                sheet
            );
        },
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: "success"
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 时间改变 得到起始时间和结束时间
        dateChange(val) {
            if (val === undefined) {
                this.errorFun("请选择查看时间！");
            } else {
                var t = val.split(" - ");
                this.postObj.dstart = t[0];
                this.postObj.dend = t[1];
                this.getData(this.postObj);
            }
        },
        // 分页器
        // 控制每页的数量
        handleSizeChange(val) {
            this.pageSize = val;
            this.tableControl();
        },
        // 页数
        handleCurrentChange(val) {
            this.currentPage = val;
            this.tableControl();
        },
        tableControl() {
            this.tableData = this.tableDataAll.slice(
                (this.currentPage - 1) * this.pageSize,
                this.currentPage * this.pageSize
            );
        },
        // 控制每页的数量
        handleSizeChange1(val) {
            this.pageSize1 = val;
            this.tableControl1();
        },
        // 页数
        handleCurrentChange1(val) {
            this.currentPage1 = val;
            this.tableControl1();
        },
        tableControl1() {
            this.tableData1 = this.tableDataAll1.slice(
                (this.currentPage1 - 1) * this.pageSize1,
                this.currentPage1 * this.pageSize1
            );
        },
        // 选择游戏的平台
        handleSelect(key, keyPath) {
            if (key === "4") {
                this.$refs.advance.filterShow = true;
                return;
            }
            if (this.postObj["server"] === "0" && this.postObj["channel"] === "0") {
                this.postObj["server"] = "0";
                this.postObj["channel"] = "0";
                this.postObj["platform"] = key;
                this.getList("updatePlatform", `platform=${key}`);
                this.getData(this.postObj);
            } else {
                if (key === "3" || key === "2" || key === "9") {
                    this.errorFun("请修改为全渠道和全服！");
                }
            }
        },
        // 选择了渠道和服务器 默认的平台
        platDefault() {
            this.postObj["platform"] = "0";
        },
        //用户菜单变换
        handle(key) {
            this.activeIndex = key;
            this.echartsDataFilter(this.activeIndex);
        },
        //设备菜单变换
        handle1(key) {
            this.activeIndex1 = key;
            this.echartsDataFilter1(this.activeIndex1);
        },
        // 获取服务器list 平台list  服务器list
        getList(url, choose) {
            var that = this;
            var pushData = function(pushArr, attr, data) {
                that[pushArr] = [];
                for (var i in data[attr]) {
                    that[pushArr].push({
                        value: i,
                        label: data[attr][i]
                    });
                }
            };
            this.$http
                .jsonp(
                    `${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=${url}`, {
                        params: { ps: choose }
                    }
                )
                .then(function(res) {
                    var data = JSON.parse(JSON.parse(res.body));
                    if (parseInt(data["res"]) === 0) {
                        // 后台select的数据
                        var lists = ["platformItmes", "channelItmes", "serverItmes"];
                        // 页面select名字
                        var nameLists = ["plats", "channels", "servers"];
                        for (var i = 0; i < lists.length; i++) {
                            if (data[lists[i]] !== undefined) {
                                pushData(nameLists[i], lists[i], data);
                            }
                        }
                    } else {
                        // this.getErrorMsg(Number(data.res));
                    }
                });
        },
        // 变成分数
        pencent() {
            var data = this.tableDataAll;
            //转换为%比 
            for (var i = 0; i < data.length; i++) {
                for (var j in data[i]) {
                    if (j === 'backrate14day' || j === 'backrate30day' || j === 'backrate7day' || j === 'backviprate14day' || j === 'backviprate30day' || j === 'backviprate7day') {
                        data[i][j] = toPercent(data[i][j]);
                    }
                }
            }
            this.tableDataAll = data;
            var data2 = this.tableDataAll1;
            //转换为%比 
            for (var i = 0; i < data2.length; i++) {
                for (var j in data2[i]) {
                    if (j === 'newUserMacRate14day' || j === 'newUserMacRate30day' || j === 'newUserMacRate7day' || j === 'oldUserMacRate14day' || j === 'oldUserMacRate30day' || j === 'oldUserMacRate7day') {
                        data2[i][j] = toPercent(data2[i][j]);
                    }
                }
            }
            this.tableDataAll1 = data2;
        },
        // 获取数据
        getData(data) {
            var that = this;
            var p = new Promise(function(resolve, reject) {
                that.dataTotal = 0;
                that.loading = true;
                that.tableData = [];
                that.tableDataAll = [];
                that.$http
                    .jsonp(
                        `${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=search`, {
                            params: {
                                ps: `dstart=${data.dstart}&dend=${data.dend}&platform=${data.platform}&channel=${data.channel}&server=${data.server}`
                            }
                        }
                    )
                    .then(function(res) {
                        resolve(res.body);
                    });
            });
            p.then(function(value) {
                that.loading = false;
                var data = JSON.parse(value);
                var d = JSON.parse(
                    data.replace(/\"\{\"/g, '{"').replace(/\"\}\"/g, '"}')
                );
                if (parseInt(d["res"]) === 0) {
                    that.dataTotal = d.backUserDatas.length;
                    that.tableDataAll = d.backUserDatas;
                    that.tableControl();

                    that.dataTotal1 = d.backDeviceDatas.length;
                    that.tableDataAll1 = d.backDeviceDatas;
                    that.tableControl1();

                    that.pencent();

                    that.allData = d;
                    that.echartsDataFilter(that.activeIndex); //将默认的菜单传入到函数中作筛选
                    that.echartsDataFilter1(that.activeIndex1); //将默认的菜单传入到函数中作筛选
                } else {
                    if (data["msg"] !== undefined) {
                        that.errorFun(data["msg"]);
                    } else {
                        that.errorFun("数据请求不正确！请联系管理员！！");
                    }
                }
            });
        },
        // 通过传入默认选择的七日或14日 30日菜单 的参数选择渲染那个图表
        echartsDataFilter(index) {
            switch (index) {
                case "1":
                    this.echartsData(this.allData.backUser07DaysChart1.jsonStr, this.allData.backUser07DaysChart2.jsonStr);
                    break;
                case "2":
                    this.echartsData(this.allData.backUser14DaysChart1.jsonStr, this.allData.backUser14DaysChart2.jsonStr);
                    break;
                case "3":
                    this.echartsData(this.allData.backUser30DaysChart1.jsonStr, this.allData.backUser30DaysChart2.jsonStr);
                    break;
            }
        },
        // 改变用户图表数据
        echartsData(d1, d2) {
            if (d1 === undefined || d2 === undefined) {
                d1 = {
                    names: [],
                    data: []
                }
            } else {
                d1.names.push(d2.names[0], d2.names[1]);
                d1.data.push(d2.data[0], d2.data[1])
            }

            // 用户数据获取到数据渲染
            this.realTimeDataChart.setOption({
                legend: {
                    data: d1["names"]
                },
                xAxis: {
                    data: d1.columnkeys
                },
                series: [{
                    name: d1.names[0],
                    data: d1.data[0]
                }, {
                    name: d1.names[1],
                    data: d1.data[1]
                }, {
                    name: d1.names[2],
                    data: d1.data[2]
                }, {
                    name: d1.names[3],
                    data: d1.data[3]
                }]
            });
        },

        // 通过传入默认选择的七日或14日 30日菜单 的参数选择渲染那个图表
        echartsDataFilter1(index) {
            switch (index) {
                case "1":
                    this.echartsData1(this.allData.backDevice07DaysChart1.jsonStr, this.allData.backDevice07DaysChart2.jsonStr);
                    break;
                case "2":
                    this.echartsData1(this.allData.backDevice14DaysChart1.jsonStr, this.allData.backDevice14DaysChart2.jsonStr);
                    break;
                case "3":
                    this.echartsData1(this.allData.backDevice30DaysChart1.jsonStr, this.allData.backDevice30DaysChart2.jsonStr);
                    break;
            }
        },
        // 改变设备图表数据
        echartsData1(d1, d2) {
            if (d1 === undefined || d2 === undefined) {
                d1 = { names: [], data: [] };
            } else {
                d1.names.push(d2.names[0], d2.names[1]);
                d1.data.push(d2.data[0], d2.data[1])
            }

            // 设备数据获取到数据渲染
            this.realTimeDataChart2.setOption({
                legend: {
                    data: d1["names"]
                },
                xAxis: {
                    data: d1.columnkeys
                },
                series: [{
                    name: d1.names[0],
                    data: d1.data[0]
                }, {
                    name: d1.names[1],
                    data: d1.data[1]
                }, {
                    name: d1.names[2],
                    data: d1.data[2]
                }, {
                    name: d1.names[3],
                    data: d1.data[3]
                }]
            });
        },
        // 用户表格排序
        sortChange(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === "descending") {
                this.tableDataAll.sort(compareObject(column.prop, false));
            } else {
                //正序
                this.tableDataAll.sort(compareObject(column.prop, true));
            }
            this.tableControl();
        },
        // 设备表格排序
        sortChange1(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === "descending") {
                this.tableDataAll1.sort(compareObject(column.prop, false));
            } else {
                //正序
                this.tableDataAll1.sort(compareObject(column.prop, true));
            }
            this.tableControl1();
        }
    },
    components: {
        "v-advance": advance
    },
    computed: {
        xlsx() {
            return this.title + ".xlsx";
        }
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem("ZULONGBIPROJECTID");
        this.DP.f = localStorage.getItem("ZULONGBIPAGEID");
        this.date = [new Date(new Date().getTime() - 7 * 86400000), new Date(new Date().getTime() - 86400000)];
        this.postObj.dstart = formatGMTDate(new Date() - 86400000 * 7, true);
        this.postObj.dend = formatGMTDate(new Date() - 86400000 * 1, true);
        // 获取到服务器 平台 渠道 list
        this.getList("initParam", "");
        // 实时图
        this.realTimeDataChart = echarts.init(
            document.getElementById("realTimeData")
        );
        this.realTimeDataChart2 = echarts.init(
            document.getElementById("realTimeData2")
        );
        this.realTimeDataChart.setOption(this.real);
        this.realTimeDataChart2.setOption(this.real);
        // 请求数据
        this.getData(this.postObj);

        this._init();
    }
};